import store from '@/store/index'
const axios = require('axios')

let baseURL = 'https://yapi.awesometool.cn/mock/9/'

const instance = axios.create({
  baseURL,
  timeout: 10000
})

let token = ''

const apis = {
  login: {
    method: 'post',
    auth: false,
    uri: 'admin/user/login'
  },
  index: {
    uri: 'admin/index',
    method: 'post'
  }
}

const request = async (api, data = {}) => {
  return new Promise((resolve, reject) => {
    if (typeof apis[api] === 'undefined') {
      reject(new Error(`api: ${api} 不存在`))
    }
    const req = apis[api]
    const uri = req['uri']
    const auth = req['auth'] ? req['auth'] : true
    const method = req['method'] ? req['method'] : 'get'
    let headers = {}
    if (auth) {
      headers['Token'] = token
    }
    headers['Accept'] = 'text'
    let server
    if (method === 'post') {
      server = instance.post(uri, data, { headers })
    } else {
      server = instance.get(uri, {
        params: {
          ...data
        },
        headers
      })
    }
    server.then((res) => {
      if (res.status === 200) {
        let { code, msg = '未知错误', data = null } = res.data
        if (typeof code !== 'undefined' && (code != 0 && code != 200)) {
          reject(msg)
        } else {
          resolve(data)
        }
      } else {
        reject(new Error(`网络错误`))
      }
    }).catch(e => {
      reject(e)
    })
  })
}

export default request

export const setToken = (t) => {
  if (t) {
    token = t
  }
  store.commit('user/setTokenAction', token)
}
